package com.landeb.shop.huo.act;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.landeb.shop.R;
import com.landeb.shop.huo.MyApplication;
import com.landeb.shop.huo.adapter.Skip4ProductFragActAdapter;
import com.landeb.shop.huo.bean.BeanProductFragLeftLv;
import com.landeb.shop.huo.bean.BeanProductFragRightGv;
import com.landeb.shop.huo.httpRequest.FragProductsRequest;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class Skip4ProductFragActivity extends BaseActivity {


    @BindView(R.id.btn_back_Skip4ProductFrag_act)
    LinearLayout mBtnBackSkip4ProductFragAct;
    @BindView(R.id.tv_title_Skip4ProductFrag_act)
    TextView mTvTitleSkip4ProductFragAct;
    @BindView(R.id.rv_Skip4ProductFrag_act)
    RecyclerView mRvSkip4ProductFragAct;
    @BindView(R.id.srl_Skip4ProductFrag_act)
    SwipeRefreshLayout mSrlSkip4ProductFragAct;

    private String cid;

    private Retrofit mRetrofit;
    private FragProductsRequest mRequest;

    private List<BeanProductFragRightGv.DataBean.ListBean> mList = new ArrayList<>();
    private Skip4ProductFragActAdapter mAdapter;

    private int page = 1;
    private boolean isRefreshing = false;
    private boolean hasNextPage = true;

    public static void toAct(Context context, String cid) {

        Intent intent = new Intent(context, Skip4ProductFragActivity.class);
        intent.putExtra("cid", cid);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_skip4_product_frag);
        ButterKnife.bind(this);

        cid = getIntent().getStringExtra("cid");

        OkHttpClient client = MyApplication.getClient();

        mRetrofit = new Retrofit.Builder()
                .baseUrl(MyApplication.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(client)
                .build();
        mRequest = mRetrofit.create(FragProductsRequest.class);

        initView();
        initData();
        initEvent();

        refresh();
        getThisTitle();
    }

    private void refresh() {

        if (isRefreshing) return;

        isRefreshing = true;
        hasNextPage = true;
        mSrlSkip4ProductFragAct.setRefreshing(true);
        page = 1;

        mRequest.getProductsData(cid, page + "", "")
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<BeanProductFragRightGv>() {
                    @Override
                    public void onCompleted() {
                        isRefreshing = false;
                        mSrlSkip4ProductFragAct.setRefreshing(false);
                    }

                    @Override
                    public void onError(Throwable e) {
                        isRefreshing = false;
                        mSrlSkip4ProductFragAct.setRefreshing(false);
                    }

                    @Override
                    public void onNext(BeanProductFragRightGv beanProductFragRightGv) {

                        if (beanProductFragRightGv.getStatus() == 0) {
                            Toast.makeText(Skip4ProductFragActivity.this, beanProductFragRightGv.getInfo(), Toast.LENGTH_SHORT).show();
                            return;
                        }

                        mList.clear();
                        mList.addAll(beanProductFragRightGv.getData().getList());
                        mAdapter.notifyDataSetChanged();

                    }
                });


    }

    private void initEvent() {

        mBtnBackSkip4ProductFragAct.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mSrlSkip4ProductFragAct.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });

        mAdapter = new Skip4ProductFragActAdapter(mList);
        mAdapter.setEnableLoadMore(true);
        mAdapter.setAutoLoadMoreSize(4);

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

                String ID = mList.get(position).getGoods_id();
                String title = mList.get(position).getName();
                String price = mList.get(position).getPrice();

                GoodDetailActivity.toAct(Skip4ProductFragActivity.this, ID, title, price);
            }
        });

        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {

//                if (!hasNextPage) return;

                loadMore();
            }
        });

        mRvSkip4ProductFragAct.setLayoutManager(new GridLayoutManager(this, 2));
        mRvSkip4ProductFragAct.setAdapter(mAdapter);

    }

    private void loadMore() {


        page++;

        mRequest.getProductsData(cid, page + "", "")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BeanProductFragRightGv>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                        Toast.makeText(Skip4ProductFragActivity.this, "数据加载失败，请重试", Toast.LENGTH_SHORT).show();

                    }

                    @Override
                    public void onNext(BeanProductFragRightGv beanProductFragRightGv) {

                        if (beanProductFragRightGv.getStatus() == 0) {
                            Toast.makeText(Skip4ProductFragActivity.this, beanProductFragRightGv.getInfo(), Toast.LENGTH_SHORT).show();
                            return;
                        }

                        mList.addAll(beanProductFragRightGv.getData().getList());
                        mAdapter.notifyDataSetChanged();


                        if (beanProductFragRightGv.getData().getMore() == 1) {
                            hasNextPage = true;
                        } else {
                            hasNextPage = false;
                        }

                    }
                });
    }

    private void getThisTitle() {


        mRequest.getProductsList()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BeanProductFragLeftLv>() {
                    @Override
                    public void onCompleted() {
                        Log.e("refreshData", "successed");
//                            isRefreshing = false;
//                            mSRL.setRefreshing(false);
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("refreshData", "onError");
                        e.printStackTrace();
//                            isRefreshing = false;
//                            mSRL.setRefreshing(false);

                        Toast.makeText(Skip4ProductFragActivity.this, "数据加载失败，请重试", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onNext(BeanProductFragLeftLv beanProductFragLeftLv) {

                        if (beanProductFragLeftLv.getStatus() == 0) {

                            Toast.makeText(Skip4ProductFragActivity.this, beanProductFragLeftLv.getInfo(), Toast.LENGTH_SHORT).show();

                            return;

                        }

                        List<BeanProductFragLeftLv.DataBean> list = beanProductFragLeftLv.getData();

                        for (BeanProductFragLeftLv.DataBean bean: list) {
                            if (bean.getId().equals(cid)){
                                mTvTitleSkip4ProductFragAct.setText(bean.getCatename());
                            }
                        }

                    }
                });

    }

    private void initData() {

    }

    private void initView() {

    }

}
